<template>
    <div class="cards-container">
        <!-- 左侧漏损数据卡片 -->
        <el-card class="leakage-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <div class="header-title">漏损数据</div>
                    <div class="date-picker-wrapper">
                        <el-tooltip effect="dark" content="当前时间仅能选择右侧时间范围内的日期" placement="top">
                            <el-icon class="date-info-icon">
                                <InfoFilled />
                            </el-icon>
                        </el-tooltip>
                        <CustomDatePicker v-model="levelTwoDate" :is-range="false" width="100px" size="small"
                            :max-date="levelOneDateRange[1]" :min-date="levelOneDateRange[0]"
                            @update:modelValue="handleLevelTwoDateChange" />
                    </div>
                </div>
            </template>

            <div class="daily-volume" v-loading="volumeLoading">
                <div class="volume-header">
                    <div class="volume-title">
                        一级表后预估漏损量：{{ chartLoading ? '正在计算' : totalVolume + 'm³' }}
                    </div>
                </div>

                <!-- 漏损区域表格 -->
                <div class="leakage-areas">
                    <div style="font-size: var(--font-size-base);margin-bottom: var(--gap-normal);">
                        二级表后区域预估漏水量({{ totalLevelTwoVolume.toFixed(2) }}m³)
                        <div class="volume-desc">
                            与总漏损之差为 {{ chartLoading ? '正在计算' : diffVolume + 'm³' }}
                            <el-tooltip effect="dark" placement="top" content="包含主管网漏损、未计量用水和表计误差">
                                <el-icon>
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </div>
                    </div>
                    <div class="area-grid">
                        <div v-for="area in mergedLeakageAreas" :key="area.areaId" class="area-item"
                            @click="handleAreaClick(area)" :class="{ 'area-item-hover': true }">
                            <div class="area-name">{{ area.name }}</div>
                            <div class="area-value">{{ area.Total }}m³/天</div>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>

        <!-- 右侧趋势图表卡片 -->
        <el-card class="trend-card" shadow="hover">
            <template #header>
                <div class="card-header">
                    <div class="header-title">漏损趋势</div>
                    <CustomDatePicker v-model="levelOneDateRange" :is-range="true" :max-days="90" width="300px"
                        size="small" @update:modelValue="handleLevelOneDateChange" />
                </div>
            </template>

            <div class="trend-chart" v-loading="chartLoading">
                <div class="chart-container">
                    <BaseChart :options="chartOptions" height="500px" />
                </div>
            </div>
        </el-card>

        <!-- 表计详情弹窗 -->
        <el-dialog v-model="dialogVisible" :title="selectedArea?.name + ' - 漏水详情'" width="600px" destroy-on-close>
            <template v-if="selectedArea">
                <div class="meter-info">
                    <div class="time-range">
                        时间范围: {{ formatDateTime(selectedArea.StartTime) }} - {{ formatDateTime(selectedArea.EndTime) }}
                    </div>

                    <div class="meters-list">
                        <div class="meters-title">表计信息:</div>
                        <el-card v-for="meter in selectedArea.Meters" :key="meter.MeterId" class="meter-card">
                            <div class="meter-header">
                                <div>
                                    <span>表计编码: {{ meterStore.getMeterByMeterId(meter.MeterId).meter_code }}</span>
                                    <!-- 供应区域supply_region -->
                                    <span class="supply-region">
                                        供应区域: {{ meterStore.getMeterByMeterId(meter.MeterId).supply_region || '未知' }}
                                    </span>
                                </div>
                                <span class="usage-value">{{ meter.Min.usage }}m³/{{ (meter.Min.duration /
                                    3600000000000).toFixed(2) }}小时</span>
                            </div>
                            <div class="meter-details">
                                <div>最小流量记录时间: {{ formatDateTime(meter.Min.record_time) }}</div>
                                <div>持续时间: {{ (meter.Min.duration / 3600000000000).toFixed(2) }} 小时</div>
                            </div>
                        </el-card>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useAreaStore } from '@/stores/area'
import { useMeterStore } from '@/stores/meter'
import { useCompanyStore } from '@/stores/company'
import dayjs from 'dayjs'
import { getWaterLevelTwoApi, getWaterLevelOneApi } from '../../../../api/waterLeakage'
import CustomDatePicker from '@/components/header/CustomDatePicker.vue'
import { QuestionFilled, InfoFilled } from '@element-plus/icons-vue'

// 状态变量
const volumeLoading = ref(false)
const chartLoading = ref(false)
const dialogVisible = ref(false)
const selectedArea = ref(null)

const areaStore = useAreaStore()
const meterStore = useMeterStore()
const companyStore = useCompanyStore()
const props = defineProps({
    meterList: {
        required: true,
        type: Array
    }
})

// 监听 meterList 的变化，变化时打印出来
watch(() => props.meterList, (newList) => {

}, { deep: true });

const mergedLeakageAreas = ref([])
const lineData = ref([])

// 日期状态
const levelTwoDate = ref(dayjs().subtract(1, 'day').startOf('day').valueOf())

const levelOneDateRange = ref([
    dayjs().subtract(2, 'week').startOf('day').valueOf(),
    dayjs().startOf('day').valueOf()
])

// 日期变化处理函数 - 优化版本
const handleLevelTwoDateChange = (date) => {
    if (date) {
        levelTwoDate.value = date;

        // 创建日期范围并获取数据
        const startDate = dayjs(date).startOf('day').valueOf();
        const endDate = dayjs(date).add(1, 'day').startOf('day').valueOf();
        getWaterLevelTwo([startDate, endDate]);
    }
}

const handleLevelOneDateChange = (dateRange) => {
    if (Array.isArray(dateRange) && dateRange.length === 2) {
        // 检查左侧选择的日期是否在新范围内
        if (levelTwoDate.value < dateRange[0] || levelTwoDate.value > dateRange[1]) {
            // 如果不在范围内，将左侧日期调整为范围的第一天
            levelTwoDate.value = dateRange[0];

            // 获取调整后的单日数据
            const startDate = dayjs(levelTwoDate.value).startOf('day').valueOf();
            const endDate = dayjs(levelTwoDate.value).add(1, 'day').startOf('day').valueOf();
            getWaterLevelTwo([startDate, endDate]);
        }

        // 获取趋势图数据
        getWaterLevelOne(dateRange);
    }
}

// 计算属性
const totalVolume = computed(() => {
    // 如果没有数据，返回0
    if (!lineData.value || lineData.value.length === 0) return 0;

    // 找到与选定日期对应的数据
    const selectedDate = dayjs(levelTwoDate.value).format("MM/DD");
    const selectedDayData = lineData.value.find(item => item.time === selectedDate);

    // 如果找到了对应日期的数据，返回该数据的值，否则返回最新数据
    return selectedDayData ? selectedDayData.value : (lineData.value.slice(-1)[0]?.value || 0);
})

const totalLevelTwoVolume = computed(() => {
    return mergedLeakageAreas.value.reduce((sum, area) => sum + Number(area.Total), 0)
})

const diffVolume = computed(() => {
    const diff = totalVolume.value - totalLevelTwoVolume.value
    return diff.toFixed(2)
})

const chartOptions = computed(() => ({
    xAxisData: lineData.value.map(item => item.time),
    series: [{
        name: '漏损量',
        type: 'line',
        data: lineData.value.map(item => item.value),
        showExtremum: true
    }],
    showMarkLine: true,
    yAxisUnit: 'm³/天'
}))

// 方法
const handleAreaClick = (area) => {
    selectedArea.value = area
    dialogVisible.value = true
}

const formatDateTime = (dateStr) => {
    return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

async function getWaterLevelTwo(dateRange) {
    mergedLeakageAreas.value = []
    try {
        volumeLoading.value = true
        let res = await getWaterLevelTwoApi({
            start_time: dateRange[0],
            end_time: dateRange[1],
            id: companyStore.currentCompany.id
        })

        // 添加防御性检查，确保 res.data 和 res.data.Areas 都存在
        if (res && res.data && res.data.Areas && Array.isArray(res.data.Areas)) {
            let data = res.data.Areas.map((item) => ({
                name: areaStore.getAreaNameById(item.AreaId),
                ...item,
                Total: (+item.Total).toFixed(2)
            }))
            mergedLeakageAreas.value = data.filter((item) => item.Total > 0)
        } else {

            mergedLeakageAreas.value = [] // 确保置为空数组
        }

        // 确保趋势数据中包含当前选定日期的数据
        updateTotalVolumeForSelectedDate(dateRange[0])
    } catch (error) {

    } finally {
        volumeLoading.value = false
    }
}

// 优化后的更新选定日期的总量数据函数
async function updateTotalVolumeForSelectedDate(selectedDate) {
    const selectedDateStr = dayjs(selectedDate).format("MM/DD")

    // 如果趋势数据中没有选定日期的数据，则获取该日期的数据
    if (!lineData.value.some(item => item.time === selectedDateStr)) {
        try {
            const singleDayRange = [
                dayjs(selectedDate).startOf('day').valueOf(),
                dayjs(selectedDate).add(1, 'day').startOf('day').valueOf()
            ]

            let res = await getWaterLevelOneApi({
                start_time: singleDayRange[0],
                end_time: singleDayRange[1],
                id: companyStore.currentCompany.id
            })

            // 如果返回了数据，添加到趋势数据中
            if (res.data && res.data.length > 0) {
                const newData = {
                    time: selectedDateStr,
                    value: (+res.data[0].total).toFixed(2)
                }

                // 添加或更新数据
                const existingIndex = lineData.value.findIndex(item => item.time === selectedDateStr)
                if (existingIndex >= 0) {
                    lineData.value[existingIndex] = newData
                } else {
                    lineData.value.push(newData)
                }
            }
        } catch (error) {

        }
    }
}

async function getWaterLevelOne(dateRange) {
    try {
        chartLoading.value = true
        let res = await getWaterLevelOneApi({
            start_time: dateRange[0],
            end_time: dateRange[1],
            id: companyStore.currentCompany.id
        })
        lineData.value = res.data.map((item) => ({
            time: dayjs(item.start_time).format("MM/DD"),
            value: (+item.total).toFixed(2)
        }))
    } catch (error) {

    } finally {
        chartLoading.value = false
    }
}

// 监听器
watch(() => companyStore.currentCompany, async () => {
    await meterStore.fetchMeterList({
        company_id: companyStore.currentCompany.id,
        type: 1
    })
    // 处理单日选择，创建一个日期范围
    const startDate = dayjs(levelTwoDate.value).startOf('day').valueOf();
    const endDate = dayjs(levelTwoDate.value).add(1, 'day').startOf('day').valueOf();
    getWaterLevelTwo([startDate, endDate]);
    getWaterLevelOne(levelOneDateRange.value);
}, { immediate: true })
</script>

<style scoped>
.cards-container {
    display: flex;
    gap: var(--gap-normal);
    height: 300px;
    margin: var(--gap-normal) 0;
}

.leakage-card {
    min-width: 600px;
    height: 300px;
    display: flex;
    flex-direction: column;
}

.leakage-card :deep(.el-card__body) {
    flex: 1;
    overflow: hidden;
    padding: var(--gap-normal);
}

.trend-card {
    flex: 1;
    min-width: 500px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.header-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
}

.date-picker-wrapper {
    display: flex;
    align-items: center;
    gap: var(--gap-small);
}

.date-info-icon {
    color: var(--el-text-color-regular);
    font-size: 14px;
    cursor: help;
}

.daily-volume {
    height: 100%;
    overflow-y: auto;
    padding-right: 8px;
}

.volume-header {
    width: 100%;
    border: 1px solid var(--el-border-color);
    border-radius: var(--el-border-radius-base);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: var(--gap-small);
    font-size: var(--font-size-base);
    margin-bottom: var(--gap-small);
    padding: 15px;
}

.volume-title {
    font-weight: 600;
    color: var(--el-text-color-primary);
}

.volume-desc {
    font-size: var(--font-size-small);
    color: var(--el-text-color-regular);
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 4px;
}

.area-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 12px;
}

.area-item {
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-light);
    border-radius: 8px;
    padding: 16px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.area-item-hover:hover {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-5);
    box-shadow: var(--el-box-shadow-light);
    transform: translateY(-2px);
}

.area-name {
    font-size: 14px;
    color: var(--el-text-color-regular);
    margin-bottom: 8px;
}

.area-value {
    font-size: 14px;
    color: var(--el-color-primary);
    font-weight: bold;
}

.trend-chart {
    height: calc(100% - 20px);
}

.chart-container {
    height: 100%;
}

/* 弹窗样式 */
.meter-info {
    padding: var(--gap-normal);
}

.time-range {
    margin-bottom: var(--gap-normal);
    color: var(--el-text-color-regular);
    font-size: 14px;
}

.meters-list {
    .meters-title {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 16px;
    }

    .meter-card {
        margin-bottom: 12px;

        .meter-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .usage-value {
            color: var(--el-color-primary);
            font-weight: 500;
        }

        .meter-details {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            line-height: 1.8;
        }

        .supply-region {
            margin-left: var(--gap-normal);
            color: var(--el-text-color-secondary);
        }
    }
}

/* 响应式设计 */
@media screen and (max-width: 1400px) {
    .cards-container {
        flex-direction: column;
        height: auto;
    }

    .leakage-card,
    .trend-card {
        width: 100%;
        min-width: auto;
        height: 300px;
    }

    .area-grid {
        grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    }
}

@media screen and (max-width: 768px) {
    .date-picker-wrapper {
        width: 100%;
        justify-content: flex-end;
    }

    .area-grid {
        grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
    }
}
</style>